import csv
import os
import sys

def csv_to_vcf(csv_file_path, vcf_file_path):
    """
    将 CSV 通讯录转换为 vCard (.vcf) 文件
    """
    # 确保输出目录存在
    os.makedirs(os.path.dirname(vcf_file_path), exist_ok=True)
    
    with open(csv_file_path, 'r', encoding='utf-8-sig') as csvfile, \
         open(vcf_file_path, 'w', encoding='utf-8') as vcf_file:

        reader = csv.DictReader(csvfile)
        fieldnames = reader.fieldnames or []
        print(fieldnames)

        # 标准化字段名（转为小写便于匹配，但保留原始）
        field_map = {f.strip().lower(): f for f in fieldnames}
        print(field_map)

        for row in reader:
            vcard = ["BEGIN:VCARD", "VERSION:3.0"]

            # 姓名处理：优先使用 First Name + Last Name
            first = row.get(field_map.get('first name', ''), '').strip()
            last = row.get(field_map.get('last name', ''), '').strip()
            full_name = row.get(field_map.get('name', ''), '').strip()

            if first or last:
                # FN: 全名
                fn = f"{first} {last}".strip()
                vcard.append(f"FN:{fn}")
                # N: 姓;名;;;
                vcard.append(f"N:{last};{first};;;")
            elif full_name:
                vcard.append(f"FN:{full_name}")
                vcard.append(f"N:{full_name};;;;")
            else:
                # 跳过无姓名的条目
                continue

            # 电话（支持多个，但这里只处理一个常见字段）
            phone_fields = ['home phone', 'home phone 2', 'business phone', 'mobile phone', 'home fax']
            for pf in phone_fields:
                if pf in field_map:
                    phone = row.get(field_map[pf], '').strip()
                    if phone:
                        phone = phone.replace(' ', '')
                        phone = phone.replace('-', '')
                        vcard.append(f"TEL;TYPE=CELL:{phone}")
                        #break  # 只取第一个找到的电话

            # 邮箱
            email_fields = ['e-mail address', 'e-mail', 'mail']
            for ef in email_fields:
                if ef in field_map:
                    email = row.get(field_map[ef], '').strip()
                    if email:
                        vcard.append(f"EMAIL;TYPE=INTERNET:{email}")
                        break

            # 公司
            org_fields = ['organization', 'company', 'org']
            for of in org_fields:
                if of in field_map:
                    org = row.get(field_map[of], '').strip()
                    if org:
                        vcard.append(f"ORG:{org}")
                        break

            # 地址（简单处理，可扩展）
            # 示例：Street, City, State, ZIP, Country
            addr_parts = []
            for addr_key in ['home street', 'city', 'state', 'zip', 'country']:
                if addr_key in field_map:
                    val = row.get(field_map[addr_key], '').strip()
                    addr_parts.append(val)
                else:
                    addr_parts.append('')
            # 如果有任意地址字段非空
            if any(addr_parts):
                # vCard 地址格式：PO Box;Extended Addr;Street;City;State;Zip;Country
                addr_str = ';'.join(addr_parts)
                vcard.append(f"ADR;TYPE=HOME:;;{addr_str}")

            vcard.append("END:VCARD")
            vcard.append("")  # 空行分隔

            vcf_file.write('\n'.join(vcard))

    print(f"✅ 转换完成！vCard 文件已保存至：{vcf_file_path}")

def main():
    if len(sys.argv) != 3:
        print("用法: python csv_to_vcf.py <输入.csv> <输出.vcf>")
        print("示例: python csv_to_vcf.py contacts.csv output/contacts.vcf")
        sys.exit(1)

    input_csv = sys.argv[1]
    output_vcf = sys.argv[2]

    if not os.path.isfile(input_csv):
        print(f"❌ 错误：找不到输入文件 {input_csv}")
        sys.exit(1)

    csv_to_vcf(input_csv, output_vcf)

if __name__ == "__main__":
    main()
